//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <EIC.h>
#include "Printer.h"
#include "uFncGDI.h"

//USEPACKAGE("o:\divers\wpdf.bpi");
#define MyPDFPrinter    ((TWPPDFPrinter*)vPDFPrinter)

#define MODULE_TAG MODULE_TAG_PRINTER
//---------------------------------------------------------------------------

#pragma package(smart_init)

//#define _PDF_PRINTQUALITY   SCREEN
//#define RESOL_PDF (short)Screen->PixelsPerInch
#define RESOL_PDF 1440
class TPrinter2 : public System::TObject
{
	typedef System::TObject inherited;

public:
	Graphics::TCanvas* FCanvas;
	Classes::TStrings* FFonts;
	int FPageNumber;
	Classes::TStrings* FPrinters;
	int FPrinterIndex;
	AnsiString FTitle;
	bool FPrinting;
	bool FAborted;
	TPrinterCapabilities FCapabilities;
	TPrinterState State;
	HDC DC;
	_devicemodeA *DevMode;
	unsigned DeviceMode;
	unsigned FPrinterHandle;
	void __fastcall SetState(TPrinterState Value);
	Graphics::TCanvas* __fastcall GetCanvas(void);
	int __fastcall GetNumCopies(void);
	Classes::TStrings* __fastcall GetFonts(void);
	HDC __fastcall GetHandle(void);
	TPrinterOrientation __fastcall GetOrientation(void);
	int __fastcall GetPageHeight(void);
	int __fastcall GetPageWidth(void);
	int __fastcall GetPrinterIndex(void);
	void __fastcall SetPrinterCapabilities(int Value);
	void __fastcall SetPrinterIndex(int Value);
	Classes::TStrings* __fastcall GetPrinters(void);
	void __fastcall SetNumCopies(int Value);
	void __fastcall SetOrientation(TPrinterOrientation Value);
	void __fastcall SetToDefaultPrinter(void);
	void __fastcall CheckPrinting(bool Value);
	void __fastcall FreePrinters(void);
	void __fastcall FreeFonts(void);

public:
	__fastcall TPrinter2(void);
	__fastcall virtual ~TPrinter2(void);
	void __fastcall Abort(void);
	void __fastcall BeginDoc(void);
	void __fastcall EndDoc(void);
	void __fastcall NewPage(void);
	void __fastcall GetPrinter(char * ADevice, char * ADriver, char * APort, unsigned &ADeviceMode);
	void __fastcall SetPrinter(char * ADevice, char * ADriver, char * APort, unsigned ADeviceMode);
	void __fastcall Refresh(void);
	__property bool Aborted = {read=FAborted, nodefault};
	__property Graphics::TCanvas* Canvas = {read=GetCanvas};
	__property TPrinterCapabilities Capabilities = {read=FCapabilities, nodefault};
	__property int Copies = {read=GetNumCopies, write=SetNumCopies, nodefault};
	__property Classes::TStrings* Fonts = {read=GetFonts};
	__property HDC Handle = {read=GetHandle, nodefault};
	__property TPrinterOrientation Orientation = {read=GetOrientation, write=SetOrientation, nodefault}
		;
	__property int PageHeight = {read=GetPageHeight, nodefault};
	__property int PageWidth = {read=GetPageWidth, nodefault};
	__property int PageNumber = {read=FPageNumber, nodefault};
	__property int PrinterIndex = {read=GetPrinterIndex, write=SetPrinterIndex, nodefault};
	__property bool Printing = {read=FPrinting, nodefault};
	__property Classes::TStrings* Printers = {read=GetPrinters};
	__property AnsiString Title = {read=FTitle, write=FTitle};
};
//---------------------------------------------------------------------------
__fastcall TEICPrinter::TEICPrinter( TEICPrinterType ePT, const AnsiString &FileName, bool bSilent):TObject()
{
ASSERT( sizeof(TPrinter) == sizeof(TPrinter2));
    try{
    m_ChangeOrientation = false;
    m_PaysagePortraitAssembles = true;
    m_ePT = ePT;
    m_LstDeviceCaps = new TStringList();
    m_bPageEnCours = false;
    hMetaDC = NULL;
    CanvasMeta = NULL;
    switch( m_ePT)
    {
        case PT_Standard :  vPDFPrinter = NULL; m_Orientation = Printer()->Orientation; break;
        case PT_PDF      :
            {
             //   WPDF_Start("Editions Informatiques Comptables","A1m2D2hT9g6d7dm6h2bh"); V1
                WPDF_Start("Editions Informatiques Comptables","A1m2D2hT9g6d7dm6h2bh");
                AnsiString File = FileName, Ext =AnsiUpperCase( ExtractFileExt( FileName));
                if( AnsiUpperCase( ExtractFileExt( FileName)) != ".PDF") File += ".PDF";
                if( FileExists( File))
                {
                    int f = FileOpen( File, fmShareExclusive );
                    if( f == -1)
                    {
                        ShowMessage( "Le fichier \"" + File + "\" est actuellement utilisé par une autre application.\n"\
                                                    "Veuillez le fermer puis rééssayer");
                        throw EAbort( "En cours d'utilisation");
                    }else FileClose( f);
                }
                Glob->nRectifPourDessin = 0;
                vPDFPrinter = new TWPPDFPrinter(Application);
              #ifndef _PDF_PRINTQUALITY == SCREEN
                if( Printer()->Printers->Count)
                    MyPDFPrinter->CanvasReference = wprefPrinter;
                else
              #endif
                    MyPDFPrinter->CanvasReference = wprefScreen;

                m_Orientation = poPortrait;
                MyPDFPrinter->Filename = File;
                if( !bSilent)
                    MyPDFPrinter->AutoLaunch = ::MessageBox( Screen->ActiveCustomForm->Handle, "Voulez vous ouvrir le fichier après sa création?", "Question", MB_YESNO)==IDYES;
#ifndef PDF_V2
                MyPDFPrinter->GraphicDriverMode << wpLazyTextOutAPI << wpUseClipping << wpSetCanvasResolution;
#endif
                if( MyPDFPrinter->Info) MyPDFPrinter->Info->Producer = "EIC";
                MyPDFPrinter->Modes << wpClipRectSupport/* << wpDontAdjustTextSpacing*/ << wpUseFontWidthArgument << wpAllowTransparentBit;
                m_bPageEnCours = false;
             /* #ifdef _DEBUG
                MyPDFPrinter->DebugMode = true;
                MyPDFPrinter->DebugMetafilePath = ExtractFilePath(MyPDFPrinter->Filename);
              #endif     */
            }break;
    }
    m_Width.DixMm = 210;
    m_Height.DixMm = 297;
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }catch( EAbort &e){throw;}
    CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------

__fastcall TEICPrinter::~TEICPrinter( )
{
    try{
    if( MyPDFPrinter)
    {
        Glob->nRectifPourDessin = RECTIF_DEFAUT;
        delete MyPDFPrinter;
    }
    delete m_LstDeviceCaps;
    }CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::BeginDoc( bool bDebutEffacable)
{
    try{
        m_AncResol = MAKELONG( (short)Glob->ResolutionX, (short)Glob->ResolutionY);
        switch( m_ePT)
        {
            case PT_Standard :  Printer()->BeginDoc();
                                m_PhysicalOffsetX = GetDeviceCaps( PHYSICALOFFSETX)-GetDeviceCaps( HORZRES)*(100.-Zoom)/200.;
                                m_PhysicalOffsetY = GetDeviceCaps( PHYSICALOFFSETY)-GetDeviceCaps( VERTRES)*(100.-Zoom)/200.;
                                Glob->ResolutionX = (int)dmPrintQuality;//GetDeviceCaps(LOGPIXELSX);
                                Glob->ResolutionY = (int)LogPixelsY;
                break;
            case PT_PDF      :
                                if( MyPDFPrinter->CanvasReference == wprefPrinter)
                                {
                                  Printer()->BeginDoc();
                                  m_Zoom = 100;
                                  m_ePT = PT_Standard;
                                  MyPDFPrinter->Tag = dmPrintQuality;
                                  m_ePT = PT_PDF;
                                  m_Zoom = 0;
                                  Printer()->Abort();
                                }else
                                  MyPDFPrinter->Tag = dmPrintQuality;

                                Glob->ResolutionX =
                                Glob->ResolutionY = (int)dmPrintQuality;//GetDeviceCaps(LOGPIXELSX);
                                MyPDFPrinter->BeginDoc();
                            TRACE("BeginDoc");
                                m_PhysicalOffsetX = 0;
                                m_PhysicalOffsetY = 0;
                                NewPage( bDebutEffacable);
                break;
        }
        #if PT_Max != 2
            #error "Type d'impression non reconnue"
        #endif
    }CATCH_EXCEPTION( TAGL)
    if( TRACEF == TRACEF_OK)
    {
        int n; AnsiString s;
        TRACEF( TAGL, "GetDeviceCaps  DRIVERVERSION[%X]", ::_GetDeviceCaps( TAGL, Canvas->Handle, DRIVERVERSION));
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, TECHNOLOGY);
        TRACEF( TAGL, "\t\t\tTECHNOLOGY[%s]",   (n==DT_PLOTTER)   ?"DT_PLOTTER"
                                                        :(n==DT_RASDISPLAY)?"DT_RASDISPLAY"
                                                        :(n==DT_RASPRINTER)?"DT_RASPRINTER"
                                                        :(n==DT_RASCAMERA) ?"DT_RASCAMERA"
                                                        :(n==DT_CHARSTREAM)?"DT_CHARSTREAM"
                                                        :(n==DT_METAFILE)  ?"DT_METAFILE"
                                                        :(n==DT_DISPFILE)  ?"DT_DISPFILE" : AnsiString(n).c_str() );
        TRACEF( TAGL, "\t\t\tHORZSIZE[%d] VERTSIZE[%d]", ::_GetDeviceCaps( TAGL, Canvas->Handle, HORZSIZE), ::_GetDeviceCaps( TAGL, Canvas->Handle, VERTSIZE));
        TRACEF( TAGL, "\t\t\tHORZRES[%d] VERTRES[%d]", ::_GetDeviceCaps( TAGL, Canvas->Handle, HORZRES), ::_GetDeviceCaps( TAGL, Canvas->Handle, VERTRES));
        TRACEF( TAGL, "\t\t\tLOGPIXELSX[%d] LOGPIXELSY[%d]", ::_GetDeviceCaps( TAGL, Canvas->Handle, LOGPIXELSX), ::_GetDeviceCaps( TAGL, Canvas->Handle, LOGPIXELSY));
        TRACEF( TAGL, "\t\t\tBITSPIXEL[%d] PLANES[%d]", ::_GetDeviceCaps( TAGL, Canvas->Handle, BITSPIXEL), ::_GetDeviceCaps( TAGL, Canvas->Handle, PLANES));
        TRACEF( TAGL, "\t\t\tNUMBRUSHES[%d] NUMPENS[%d] NUMFONTS[%d] NUMCOLORS[%d]",
               ::_GetDeviceCaps( TAGL, Canvas->Handle, NUMBRUSHES), ::_GetDeviceCaps( TAGL, Canvas->Handle, NUMPENS), ::_GetDeviceCaps( TAGL, Canvas->Handle, NUMFONTS), ::_GetDeviceCaps( TAGL, Canvas->Handle, NUMCOLORS));
        TRACEF( TAGL, "\t\t\tASPECTX[%d] NUMPENS[%d] ASPECTXY[%d]",
               ::_GetDeviceCaps( TAGL, Canvas->Handle, ASPECTX), ::_GetDeviceCaps( TAGL, Canvas->Handle, ASPECTY), ::_GetDeviceCaps( TAGL, Canvas->Handle, ASPECTXY));
        TRACEF( TAGL, "\t\t\tCLIPCAPS[%d] SIZEPALETTE[%d] NUMRESERVED[%d] COLORRES[%d]",
               ::_GetDeviceCaps( TAGL, Canvas->Handle, CLIPCAPS), ::_GetDeviceCaps( TAGL, Canvas->Handle, SIZEPALETTE), ::_GetDeviceCaps( TAGL, Canvas->Handle, NUMRESERVED), ::_GetDeviceCaps( TAGL, Canvas->Handle, COLORRES));
        TRACEF( TAGL, "\t\t\tPHYSICALWIDTH[%d] PHYSICALHEIGHT[%d] PHYSICALOFFSETX[%d] PHYSICALOFFSETY[%d]",
               ::_GetDeviceCaps( TAGL, Canvas->Handle, PHYSICALWIDTH), ::_GetDeviceCaps( TAGL, Canvas->Handle, PHYSICALHEIGHT), ::_GetDeviceCaps( TAGL, Canvas->Handle, PHYSICALOFFSETX), ::_GetDeviceCaps( TAGL, Canvas->Handle, PHYSICALOFFSETY));
        TRACEF( TAGL, "\t\t\tSCALINGFACTORX[%d] SCALINGFACTORY[%d] BLTALIGNMENT[%d]",
               ::_GetDeviceCaps( TAGL, Canvas->Handle, SCALINGFACTORX), ::_GetDeviceCaps( TAGL, Canvas->Handle, SCALINGFACTORY), ::_GetDeviceCaps( TAGL, Canvas->Handle, BLTALIGNMENT));

        TRACEF( TAGL, "\t\t\tSHADEBLENDCAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, SHADEBLENDCAPS);
        TRACEF( TAGL, "\t\t\t\tSB_CONST_ALPHA   [%d]",   n&SB_CONST_ALPHA);
        TRACEF( TAGL, "\t\t\t\tSB_GRAD_RECT     [%d]",   n&SB_GRAD_RECT);
        TRACEF( TAGL, "\t\t\t\tSB_GRAD_TRI      [%d]",   n&SB_GRAD_TRI);
        TRACEF( TAGL, "\t\t\t\tSB_NONE          [%d]",   n&SB_NONE);
        TRACEF( TAGL, "\t\t\t\tSB_PIXEL_ALPHA   [%d]",   n&SB_PIXEL_ALPHA);
        TRACEF( TAGL, "\t\t\t\tSB_PREMULT_ALPHA [%d]",   n&SB_PREMULT_ALPHA);

        TRACEF( TAGL, "\t\t\tRASTERCAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, RASTERCAPS);
        TRACEF( TAGL, "\t\t\t\tRC_BANDING       [%d]",   n&RC_BANDING       );
        TRACEF( TAGL, "\t\t\t\tRC_BITBLT        [%d]",   n&RC_BITBLT        );
        TRACEF( TAGL, "\t\t\t\tRC_BITMAP64      [%d]",   n&RC_BITMAP64      );
        TRACEF( TAGL, "\t\t\t\tRC_DI_BITMAP     [%d]",   n&RC_DI_BITMAP     );
        TRACEF( TAGL, "\t\t\t\tRC_DIBTODEV      [%d]",   n&RC_DIBTODEV      );
        TRACEF( TAGL, "\t\t\t\tRC_FLOODFILL     [%d]",   n&RC_FLOODFILL     );
        TRACEF( TAGL, "\t\t\t\tRC_PALETTE       [%d]",   n&RC_PALETTE       );
        TRACEF( TAGL, "\t\t\t\tRC_SCALING       [%d]",   n&RC_SCALING       );
        TRACEF( TAGL, "\t\t\t\tRC_STRETCHBLT    [%d]",   n&RC_STRETCHBLT    );
        TRACEF( TAGL, "\t\t\t\tRC_STRETCHDIB    [%d]",   n&RC_STRETCHDIB    );

        TRACEF( TAGL, "\t\t\tCURVECAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, CURVECAPS);
        TRACEF( TAGL, "\t\t\t\tCC_NONE          [%d]",   n&CC_NONE          );
        TRACEF( TAGL, "\t\t\t\tCC_CHORD         [%d]",   n&CC_CHORD         );
        TRACEF( TAGL, "\t\t\t\tCC_CIRCLES       [%d]",   n&CC_CIRCLES       );
        TRACEF( TAGL, "\t\t\t\tCC_ELLIPSES      [%d]",   n&CC_ELLIPSES      );
        TRACEF( TAGL, "\t\t\t\tCC_INTERIORS     [%d]",   n&CC_INTERIORS     );
        TRACEF( TAGL, "\t\t\t\tCC_PIE           [%d]",   n&CC_PIE           );
        TRACEF( TAGL, "\t\t\t\tCC_ROUNDRECT     [%d]",   n&CC_ROUNDRECT     );
        TRACEF( TAGL, "\t\t\t\tCC_STYLED        [%d]",   n&CC_STYLED        );
        TRACEF( TAGL, "\t\t\t\tCC_WIDE          [%d]",   n&CC_WIDE          );
        TRACEF( TAGL, "\t\t\t\tCC_WIDESTYLED    [%d]",   n&CC_WIDESTYLED    );

        TRACEF( TAGL, "\t\t\tLINECAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, LINECAPS);
        TRACEF( TAGL, "\t\t\t\tLC_NONE          [%d]",   n&LC_NONE          );
        TRACEF( TAGL, "\t\t\t\tLC_INTERIORS     [%d]",   n&LC_INTERIORS     );
        TRACEF( TAGL, "\t\t\t\tLC_MARKER        [%d]",   n&LC_MARKER        );
        TRACEF( TAGL, "\t\t\t\tLC_POLYLINE      [%d]",   n&LC_POLYLINE      );
        TRACEF( TAGL, "\t\t\t\tLC_POLYMARKER    [%d]",   n&LC_POLYMARKER    );
        TRACEF( TAGL, "\t\t\t\tLC_STYLED        [%d]",   n&LC_STYLED        );
        TRACEF( TAGL, "\t\t\t\tLC_WIDE          [%d]",   n&LC_WIDE          );
        TRACEF( TAGL, "\t\t\t\tLC_WIDESTYLED    [%d]",   n&LC_WIDESTYLED    );

        TRACEF( TAGL, "\t\t\tPOLYGONALCAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, POLYGONALCAPS);
        TRACEF( TAGL, "\t\t\t\tPC_NONE          [%d]",   n&PC_NONE          );
        TRACEF( TAGL, "\t\t\t\tPC_INTERIORS     [%d]",   n&PC_INTERIORS     );
        TRACEF( TAGL, "\t\t\t\tPC_POLYGON       [%d]",   n&PC_POLYGON       );
        TRACEF( TAGL, "\t\t\t\tPC_RECTANGLE     [%d]",   n&PC_RECTANGLE     );
        TRACEF( TAGL, "\t\t\t\tPC_SCANLINE      [%d]",   n&PC_SCANLINE      );
        TRACEF( TAGL, "\t\t\t\tPC_STYLED        [%d]",   n&PC_STYLED        );
        TRACEF( TAGL, "\t\t\t\tPC_WIDE          [%d]",   n&PC_WIDE          );
        TRACEF( TAGL, "\t\t\t\tPC_WIDESTYLED    [%d]",   n&PC_WIDESTYLED    );
        TRACEF( TAGL, "\t\t\t\tPC_WINDPOLYGON   [%d]",   n&PC_WINDPOLYGON   );

        TRACEF( TAGL, "\t\t\tTEXTCAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, TEXTCAPS);
        TRACEF( TAGL, "\t\t\t\tTC_OP_CHARACTER  [%d]",   n&TC_OP_CHARACTER  );
        TRACEF( TAGL, "\t\t\t\tTC_OP_STROKE     [%d]",   n&TC_OP_STROKE     );
        TRACEF( TAGL, "\t\t\t\tTC_CP_STROKE     [%d]",   n&TC_CP_STROKE     );
        TRACEF( TAGL, "\t\t\t\tTC_CR_90         [%d]",   n&TC_CR_90         );
        TRACEF( TAGL, "\t\t\t\tTC_CR_ANY        [%d]",   n&TC_CR_ANY        );
        TRACEF( TAGL, "\t\t\t\tTC_SF_X_YINDEP   [%d]",   n&TC_SF_X_YINDEP   );
        TRACEF( TAGL, "\t\t\t\tTC_SA_DOUBLE     [%d]",   n&TC_SA_DOUBLE     );
        TRACEF( TAGL, "\t\t\t\tTC_SA_INTEGER    [%d]",   n&TC_SA_INTEGER    );
        TRACEF( TAGL, "\t\t\t\tTC_SA_CONTIN     [%d]",   n&TC_SA_CONTIN     );
        TRACEF( TAGL, "\t\t\t\tTC_EA_DOUBLE     [%d]",   n&TC_EA_DOUBLE     );
        TRACEF( TAGL, "\t\t\t\tTC_IA_ABLE       [%d]",   n&TC_IA_ABLE       );
        TRACEF( TAGL, "\t\t\t\tTC_UA_ABLE       [%d]",   n&TC_UA_ABLE       );
        TRACEF( TAGL, "\t\t\t\tTC_SO_ABLE       [%d]",   n&TC_SO_ABLE       );
        TRACEF( TAGL, "\t\t\t\tTC_RA_ABLE       [%d]",   n&TC_RA_ABLE       );
        TRACEF( TAGL, "\t\t\t\tTC_VA_ABLE       [%d]",   n&TC_VA_ABLE       );
        TRACEF( TAGL, "\t\t\t\tTC_RESERVED      [%d]",   n&TC_RESERVED      );
        TRACEF( TAGL, "\t\t\t\tTC_SCROLLBLT     [%d]",   n&TC_SCROLLBLT     );

        TRACEF( TAGL, "\t\t\tCOLORMGMTCAPS");
        n = ::_GetDeviceCaps( TAGL, Canvas->Handle, COLORMGMTCAPS);
        TRACEF( TAGL, "\t\t\t\tCM_CMYK_COLOR    [%d]",   n&CM_CMYK_COLOR    );
        TRACEF( TAGL, "\t\t\t\tCM_DEVICE_ICM    [%d]",   n&CM_DEVICE_ICM    );
        TRACEF( TAGL, "\t\t\t\tCM_GAMMA_RAMP    [%d]",   n&CM_GAMMA_RAMP    );
        TRACEF( TAGL, "\t\t\t\tCM_NONE          [%d]",   n&CM_NONE          );
        TRACEF( TAGL, "BeginDoc" );
    }
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::EndDoc(void)
{
TRACEF( TAGL, "Avant EndDoc" );
    try{
    switch( m_ePT)
    {
        case PT_Standard :  Printer()->EndDoc();
                            Printer()->Copies = 1; //permet de décharger certains drivers (Lanier)
                 //           Printer()->PrinterIndex = Printer()->PrinterIndex; //permet de décharger certains drivers (Lanier)
            break;
        case PT_PDF      :  if( m_bPageEnCours)
                            {
                                TRACE("EndPage");
                                if( hMetaDC)
                                    ValideDebutPage( true);  
                                MyPDFPrinter->EndPage();
                            }
                            m_bPageEnCours = false;
                            TRACE("EndDoc");
                            MyPDFPrinter->EndDoc();
            break;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
        Glob->ResolutionX = LOWORD( m_AncResol);
        Glob->ResolutionY = HIWORD( m_AncResol);
    }CATCH_EXCEPTION( TAGL)
TRACEF( TAGL, "Après EndDoc" );
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::Abort(void)
{
    try{
    switch( m_ePT)
    {
        case PT_Standard :  Printer()->Abort();  break;
        case PT_PDF      :  MyPDFPrinter->Abort();  MyPDFPrinter->EndDoc(); m_bPageEnCours = false; break;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------
void __fastcall TEICPrinter::NewPage(bool bDebutEffacable)
{
double dX, dY;
try{
    switch( m_ePT)
    {
        case PT_Standard :
                           if( m_ChangeOrientation)
                           { // si il faut changer d'orientation entre 2 pages, il faut passer outre les fonctions VCL
                             DEVMODE *pDevMode = 0;
                             HGLOBAL  hDeviceMode = 0;
                             HANDLE   PrinterHandle;//   ' handle to printer
                             char     ADevice[225], ADriver[225], APort[225];
                             Printer()->GetPrinter( ADevice, ADriver, APort, (UINT)hDeviceMode);

                             TPrinter *p = Printer();
                             TPrinter2 *ps = (TPrinter2 *)(long)p;
                             ::_EndPage(TAGL, ps->DC);

                 //          ' Get a handle to the printer.
                             ::_OpenPrinter(TAGL, ADevice, &PrinterHandle, 0);
                             // Reserve memory for the actual size of the DEVMODE
                             pDevMode = (DEVMODE*)::_GlobalLock( TAGL, (HGLOBAL)hDeviceMode);

                             // Change the appropriate member in the DevMode.
                             // In this case, you want to change the paper bin and
                             // orientation.
                             pDevMode->dmOrientation = (m_Orientation==poPortrait)? DMORIENT_PORTRAIT : DMORIENT_LANDSCAPE;
                             // Set the dmFields bit flag to indicate what you're changing.
                             pDevMode->dmFields = pDevMode->dmFields | DM_ORIENTATION;

                             ::_DocumentProperties(TAGL, 0, PrinterHandle, ADevice, pDevMode, pDevMode, DM_IN_BUFFER & DM_OUT_BUFFER);

                             ::_ResetDC(TAGL, p->Canvas->Handle, pDevMode); //   Reset the DEVMODE

                             // Close the handle when you're done with it.
                             ::_ClosePrinter( TAGL, PrinterHandle);
                             ::_GlobalUnlock( TAGL, (HGLOBAL)hDeviceMode); pDevMode = NULL;

                             ::_StartPage(TAGL, ps->DC);
                             ps->FPageNumber++;
                             p->Canvas->Refresh();
                           }else
                             Printer()->NewPage();
                           m_ChangeOrientation = false;
                           ::_SetMapMode( TAGL, Canvas->Handle, MM_TEXT);
                        break;
        case PT_PDF      : if( m_bPageEnCours)
                           {
                                if( hMetaDC)
                                    ValideDebutPage( true);
                                MyPDFPrinter->EndPage();
                           }
                           ValideDebutPage( !bDebutEffacable);
                           m_bPageEnCours = true;
                        break;
    }
    //ATTENTION sous 98 lorsqu'il n'y a pas d'imprimantes, le canvas peut etre à 0
    // Solution : installer un driver d'imprimante
    ::_SelectClipRgn( TAGL, Canvas->Handle, NULL);
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------
void __fastcall TEICPrinter::ValideDebutPage(bool bOK)
{
  HENHMETAFILE hemf;
    try{
        switch( m_ePT)
        {
            case PT_Standard :
                break;
            case PT_PDF      :
            {
                if( hMetaDC)
                    {
                    hemf = ::_CloseEnhMetaFile( TAGL, hMetaDC );
                    }

                if( bOK)
                {
                    Glob->ResolutionX =
                    Glob->ResolutionY = (int)dmPrintQuality;//GetDeviceCaps(LOGPIXELSX);
//                    MyPDFPrinter->StartPage( m_Width.PixelsX, m_Height.PixelsY,
//                                             dmPrintQuality, dmPrintQuality, (m_Orientation==poLandscape)?WPDF_PAGE_LANDSCAPE:WPDF_PAGE_PORTRAIT);
                    MyPDFPrinter->StartPage( (m_Orientation==poLandscape)?m_Height.PixelsY:m_Width.PixelsX, (m_Orientation==poLandscape)?m_Width.PixelsY:m_Height.PixelsY,
                                             dmPrintQuality, dmPrintQuality, /*(m_Orientation==poLandscape)?WPDF_PAGE_LANDSCAPE:*/WPDF_PAGE_PORTRAIT);
                    /*MyPDFPrinter->Canvas->Brush->Color = clRed;
                    MyPDFPrinter->DrawGraphicFile( m_Width.PixelsX - 10, 0, m_Width.PixelsX, m_Height.PixelsY, "x:\\logoef.bmp");
                    MyPDFPrinter->Canvas->Brush->Color = clGreen;
                    MyPDFPrinter->DrawGraphicFile( 0, 0, 10, m_Height.PixelsY, "x:\\logoef.bmp");    */
                    if( hMetaDC)
                    {
                      RECT r = {0, 0, m_Width.PixelsX, m_Height.PixelsY};
                     // RECT r = Rc.RECTPixels;     r.bottom++;// permet de toujours imprimer les lignes de fin de tableau
                      ::_PlayEnhMetaFile( TAGL, MyPDFPrinter->Canvas->Handle, hemf, &r);
                        //MyPDFPrinter->UseWatermark( m_WatermarkEnCours);
                        //m_WatermarkEnCours = EmptyStr;
                      ::_DeleteEnhMetaFile(TAGL, hemf);
                      if(CanvasMeta)
                        {
                        CanvasMeta->Handle = NULL;
                        delete CanvasMeta;
                        CanvasMeta = NULL;
                        }
                      hMetaDC = NULL;
                      hemf = NULL;
                    }

                }else{
                    Glob->ResolutionX =
                    Glob->ResolutionY = (int)dmPrintQuality;//GetDeviceCaps(LOGPIXELSX);

                 /*   if( !m_WatermarkEnCours.IsEmpty())
                        m_WatermarkEnCours += "_";
                    else
                        m_WatermarkEnCours = AnsiString("DEBUT_PAGE_") + (MyPDFPrinter->PageNumber+1);    */

                    hMetaDC = ::_MyCreateEnhMetaFile( TAGL, m_Width/*Rc.Width*/, m_Height/*Rc.Height*/, dmPrintQuality);
                    CanvasMeta = new TCanvas();
                    CanvasMeta->Handle = hMetaDC;
                    RECT r = {0, 0, m_Width.PixelsX, m_Height.PixelsY};
                    FillRect( hMetaDC, &r, GetStockObject(WHITE_BRUSH	));
                    /*MyPDFPrinter->StartWatermark( m_WatermarkEnCours, (m_Orientation==poLandscape)?m_Height.PixelsY:m_Width.PixelsX, (m_Orientation==poLandscape)?m_Width.PixelsY:m_Height.PixelsY,
                                                  dmPrintQuality,dmPrintQuality);
//                                                  int i = m_Width.PixelsX / 150;   */
                }
                m_bPageEnCours = true;
                ::_SelectClipRgn( TAGL, Canvas->Handle, NULL);
               } break;
        }
        #if PT_Max != 2
            #error "Type d'impression non reconnue"
        #endif
    }CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------

bool __fastcall TEICPrinter::GetPrinting()const
{
    try{
    switch( m_ePT)
    {
        case PT_Standard :  return Printer()->Printing;
        case PT_PDF      :  return m_bPageEnCours;//MyPDFPrinter->Printing;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }CATCH_EXCEPTION( TAGL)
    return false;
}
//---------------------------------------------------------------------------

Graphics::TCanvas* __fastcall TEICPrinter::GetCanvas(void)const
{
    try{
        if( Printing)
        {
            switch( m_ePT)
            {
                case PT_Standard :  return Printer()->Canvas;
                case PT_PDF      :  return CanvasMeta?CanvasMeta:MyPDFPrinter->Canvas;
            }
            #if PT_Max != 2
                #error "Type d'impression non reconnue"
            #endif
        }
    }catch(...)
    {
        return NULL;
    }
    return NULL;
}
//---------------------------------------------------------------------------

TPrinterOrientation __fastcall TEICPrinter::GetOrientation(void)const
{
    try{
    switch( m_ePT)
    {
        case PT_Standard : ASSERT( m_Orientation == Printer()->Orientation); return Printer()->Orientation;
        case PT_PDF      :  return m_Orientation;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }CATCH_EXCEPTION( TAGL)
    return poPortrait;
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::SetOrientation(TPrinterOrientation Value)
{
    try{
    if( Value != m_Orientation)
    {
      switch( m_ePT)
      {
        case PT_Standard :
          if( Printer()->Printing)
          {
            m_ChangeOrientation = true;
          }else
            Printer()->Orientation = Value;
        break;
        case PT_PDF      :  {// TCoordonnee d = m_Width; m_Width = m_Height; m_Height = d;
                            }break;
      }
      #if PT_Max != 2
        #error "Type d'impression non reconnue"
      #endif
      m_Orientation = Value;
    }
    }CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::SetTitle(const AnsiString& Title)
{
    try{
    switch( m_ePT)
    {
        case PT_Standard :  Printer()->Title = Title;  break;
        case PT_PDF      :  if( MyPDFPrinter->Info) MyPDFPrinter->Info->Title = Title;  break;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }CATCH_EXCEPTION( TAGL)
}
//---------------------------------------------------------------------------
bool __fastcall TEICPrinter::SelectPrinter( const AnsiString &NomImprimante)
{
  int i = Printer()->Printers->IndexOf(NomImprimante);
  if( i != -1)
  {
    Printer()->PrinterIndex = i;
  }
  else
  {
    EICErreur( "L'imprimante "+NomImprimante+" n'est pas correctement installée");
    return false;
  }
  return true;
}
//---------------------------------------------------------------------------
short __fastcall TEICPrinter::GetLogPixelsY()
{
    return GetDeviceCaps(LOGPIXELSY) * Zoom/100.;
}

//---------------------------------------------------------------------------
short __fastcall TEICPrinter::GetPrintQuality()const
{
    short sdmPrintQuality=0;
    try{
    switch( m_ePT)
    {
        case PT_Standard :
            {
                if( Printing)
                {
                    sdmPrintQuality = GetDeviceCaps(LOGPIXELSX);
                    if( !sdmPrintQuality) goto autreMethode;
                }else
                {  autreMethode:
                    char     ADevice[225], ADriver[225], APort[225];
                    DEVMODE *pDevMode = 0;
                    HGLOBAL  hDeviceMode = 0;
                    Printer()->GetPrinter( ADevice, ADriver, APort, (UINT)hDeviceMode);
                    if( hDeviceMode == 0)  throw *new Exception( "ActImprimerExecute (DeviceMode=0)");
                    pDevMode = (DEVMODE*)::_GlobalLock( TAGL, (HGLOBAL)hDeviceMode);
                    if( pDevMode == 0)     throw *new Exception( "ActImprimerExecute (pDevMode=0)");
                    sdmPrintQuality = pDevMode->dmPrintQuality;
                    ::_GlobalUnlock( TAGL, (HGLOBAL)hDeviceMode); pDevMode = NULL;
                    if( sdmPrintQuality <= 0)
                    {
                        sdmPrintQuality = Glob->ResolEcran;
                    }
//                    if( !sdmPrintQuality) sdmPrintQuality = -1;
                }
                sdmPrintQuality *= Zoom/100.;
            }break;
/*#ifdef _PDF_PRINTQUALITY == SCREEN
        case PT_PDF      :  sdmPrintQuality = RESOL_PDF;    break;
#else
        case PT_PDF      :  sdmPrintQuality = 600;                             break;
#endif*/
        case PT_PDF      :
            if( MyPDFPrinter->CanvasReference == wprefScreen)
                sdmPrintQuality = Glob->ResolEcran;
            else if( (_WINPLATFORM == VP_WINDOWS_95_98) && (MyPDFPrinter->CanvasReference == wprefPrinter))
            {
                sdmPrintQuality = ::_GetDeviceCaps( TAGL, Printer()->Handle, LOGPIXELSX);
                if( !sdmPrintQuality)
                {   MyPDFPrinter->CanvasReference = wprefScreen;
                    return GetPrintQuality();
                }
            }else
                sdmPrintQuality = RESOL_PDF;
        break;

    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    }CATCH_EXCEPTION( TAGL)
    return sdmPrintQuality;
}
//---------------------------------------------------------------------------
double __fastcall TEICPrinter::GetResolPourRTF()const
{
    try{
        switch( m_ePT)
        {
            case PT_PDF :
                return MyPDFPrinter->Tag;//600;//RESOL_PDF - GetPrintQuality();
//            break;
        }
    }CATCH_EXCEPTION( TAGL)
    return 1;
}
//---------------------------------------------------------------------------

bool __fastcall TEICPrinter::CopieSupport( void)
{
    switch( m_ePT)
    {
        case PT_Standard : return !GED_IsPrinterGED( Printer()->Printers->Strings[ Printer()->PrinterIndex]);
        case PT_PDF      : return false;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
    return false;
}
//---------------------------------------------------------------------------
short __fastcall TEICPrinter::GetCopies(void)
{
    if( CopieSupport())
    {
        switch( m_ePT)
        {
            case PT_Standard : return (short)Printer()->Copies;
            case PT_PDF      : break;
        }
        #if PT_Max != 2
            #error "Type d'impression non reconnue"
        #endif
    }
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall TEICPrinter::SetCopies(const short Copies)
{
    if( !CopieSupport()) return;
    switch( m_ePT)
    {
        case PT_Standard : Printer()->Copies = Copies; break;
        case PT_PDF      : break;
    }
    #if PT_Max != 2
        #error "Type d'impression non reconnue"
    #endif
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::SetWidth(const TCoordonnee Width)
{
    m_Width = Width;
    switch( m_ePT)
    {
        case PT_Standard : break;
        case PT_PDF      : break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::SetHeight(const TCoordonnee Height)
{
    m_Height = Height;
    switch( m_ePT)
    {
        case PT_Standard : break;
        case PT_PDF      : break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TEICPrinter::SetTypePapier(int TypePapier)
{
    m_TypePapier = TypePapier;
    switch( m_ePT)
    {
        case PT_Standard : break;
        case PT_PDF      : break;
    }
}
//---------------------------------------------------------------------------
void __fastcall TEICPrinter::SetZoom(int z)
{
    switch( m_ePT)
    {
        case PT_Standard : m_Zoom = z; break;
        case PT_PDF      : break;
    }

}
//---------------------------------------------------------------------------
void __fastcall TEICPrinter::SetPaysagePortraitAssembles( bool b)
{
    switch( m_ePT)
    {
        case PT_Standard : m_PaysagePortraitAssembles = b; break;
        case PT_PDF      : break;
    }

}
//---------------------------------------------------------------------------
int __fastcall TEICPrinter::GetDeviceCaps( int nIndex)const
{
    int Result = 0;
    try{
    Result = m_LstDeviceCaps->IndexOf( AnsiString( nIndex));
    if( Result == -1)
    {
        Result = 0;
        if( Canvas)
        {
            Result = ::_GetDeviceCaps( TAGL, Canvas->Handle, nIndex);
//#ifndef PDF_V2
            if( m_ePT == PT_PDF)
            {
                switch( nIndex)
                {
                    case RASTERCAPS	: Result = Result & ~RC_STRETCHDIB; break;
 //                   case CLIPCAPS   : Result = false;                   break;
                }
            }
//#endif
        }
        m_LstDeviceCaps->AddObject(AnsiString(nIndex), (TObject*)Result);
    }else
    {
        Result = (int)m_LstDeviceCaps->Objects[Result];
    }
    }CATCH_EXCEPTION( TAGL)
    return Result;
}
void __fastcall TEICPrinter::RectifieCoordonnees( TRect &Rect)
{
    Rect.Left   -= m_PhysicalOffsetX;
    Rect.Right  -= m_PhysicalOffsetX;
    Rect.Top    -= m_PhysicalOffsetY;
    Rect.Bottom -= m_PhysicalOffsetY;
}
void __fastcall TEICPrinter::RectifieCoordonnees( RECT &Rect)
{
    Rect.left   -= m_PhysicalOffsetX;
    Rect.right  -= m_PhysicalOffsetX;
    Rect.top    -= m_PhysicalOffsetY;
    Rect.bottom -= m_PhysicalOffsetY;
}
void __fastcall TEICPrinter::RectifieCoordonnees( TPoint &pt)
{
    pt.x -= m_PhysicalOffsetX;
    pt.y -= m_PhysicalOffsetY;
}

void __fastcall TEICPrinter::DrawEnhMetaFile(int x, int y, HENHMETAFILE meta)
{
    switch( m_ePT)
    {
        case PT_PDF      : MyPDFPrinter->DrawMetafile(x, y, (unsigned)meta); break;
        default : ASSERT( false);
    }
}
void __fastcall TEICPrinter::DrawTransparentBitmap( Graphics::TBitmap *Bmp,
                                                    short xStart, short yStart, short w, short h, COLORREF cTransparentColor)
{
    switch( m_ePT)
    {
        case PT_PDF      :
             ASSERT( !CanvasMeta);
             MyPDFPrinter->Canvas->CopyMode = cTransparentColor?cmSrcAnd:cmSrcPaint;
             MyPDFPrinter->DrawBitmap( xStart, yStart, w, h, (UINT)Bmp->Handle);
            break;
        default : ASSERT( false);
    }

}
void __fastcall TEICPrinter::DrawTGraphic( Graphics::TGraphic *Graph, const TRect &r)
{
    switch( m_ePT)
    {
        case PT_PDF      :
        {
             if( CanvasMeta)
             {
                CanvasMeta->StretchDraw( r, Graph);
             }else
             {
                Graphics::TGraphic *g = Graph;
                if( !dynamic_cast<Graphics::TBitmap*>(Graph))
                {
                    g = new Graphics::TBitmap();
                    g->Width  = Graph->Width;
                    g->Height = Graph->Height;
                    ((Graphics::TBitmap*)g)->Canvas->Draw( 0, 0, Graph);
                }
                MyPDFPrinter->Canvas->StretchDraw( r, g);
//            	  MyPDFPrinter->DrawTGraphic(r.Left, r.Top, r.Width(), r.Height(), g);
                  if( g != Graph)
                    delete g;
              }
        }break;
        default : ASSERT( false);
    }
}